from django.db import models
from django.db.models import Q
from rest_framework import serializers
from drf_spectacular.utils import extend_schema_field
from drf_spectacular.types import OpenApiTypes
from .models import Notification, NotificationTemplate, WechatSubscription, MessageRecord
from user_app.models import User
from user_app.serializers import UserSerializer
from order_app.serializers import OrderListSerializer


class NotificationSerializer(serializers.ModelSerializer):
    """通知序列化器"""
    
    recipient = UserSerializer(read_only=True)
    notification_type_display = serializers.CharField(source='get_notification_type_display', read_only=True)
    level_display = serializers.CharField(source='get_level_display', read_only=True)
    related_order = OrderListSerializer(read_only=True)
    
    class Meta:
        model = Notification
        fields = [
            'id', 'recipient', 'title', 'content',
            'notification_type', 'notification_type_display',
            'level', 'level_display', 'related_order',
            'is_read', 'read_at', 'created_at'
        ]
        read_only_fields = [
            'id', 'recipient', 'notification_type_display',
            'level_display', 'created_at'
        ]


class NotificationCreateSerializer(serializers.ModelSerializer):
    """平台通知创建序列化器
    
    用于创建平台级别的通知，仅限管理员使用。
    不再关联具体订单，仅包含通知的基本信息。
    """
    
    class Meta:
        model = Notification
        fields = [
            'recipient', 'title', 'content',
            'notification_type', 'level'
        ]


class NotificationTemplateSerializer(serializers.ModelSerializer):
    """通知模板序列化器"""
    
    notification_type_display = serializers.CharField(source='get_notification_type_display', read_only=True)
    level_display = serializers.CharField(source='get_level_display', read_only=True)
    
    class Meta:
        model = NotificationTemplate
        fields = [
            'id', 'code', 'title_template', 'content_template',
            'notification_type', 'notification_type_display',
            'level', 'level_display', 'wechat_template_id',
            'is_active', 'remark', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'notification_type_display', 'level_display',
            'created_at', 'updated_at'
        ]


class WechatSubscriptionSerializer(serializers.ModelSerializer):
    """微信订阅消息序列化器"""
    
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = WechatSubscription
        fields = [
            'id', 'user', 'template_id', 'subscription_id',
            'is_active', 'expires_at', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'user', 'created_at', 'updated_at'
        ]


class WechatSubscriptionCreateSerializer(serializers.ModelSerializer):
    """微信订阅消息创建序列化器"""
    
    class Meta:
        model = WechatSubscription
        fields = ['template_id', 'subscription_id', 'expires_at']


class MessageRecordSerializer(serializers.ModelSerializer):
    """消息发送记录序列化器"""
    
    notification = NotificationSerializer(read_only=True)
    message_type_display = serializers.CharField(source='get_message_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = MessageRecord
        fields = [
            'id', 'notification', 'message_type', 'message_type_display',
            'recipient_id', 'title', 'content', 'template_data',
            'status', 'status_display', 'error_message', 'external_id',
            'created_at', 'sent_at', 'delivered_at'
        ]
        read_only_fields = [
            'id', 'message_type_display', 'status_display',
            'created_at', 'sent_at', 'delivered_at'
        ]


class NotificationListSerializer(serializers.ModelSerializer):
    """通知列表序列化器"""
    
    notification_type_display = serializers.CharField(source='get_notification_type_display', read_only=True)
    level_display = serializers.CharField(source='get_level_display', read_only=True)
    
    # 添加订单相关信息字段
    order_id = serializers.IntegerField(source='related_order.id', read_only=True, allow_null=True)
    recipient_role = serializers.SerializerMethodField()
    recipient_real_name = serializers.SerializerMethodField()
    from_location = serializers.CharField(source='related_order.from_location', read_only=True, allow_null=True)
    expected_delivery_time = serializers.DateTimeField(source='related_order.expected_delivery_time', read_only=True, allow_null=True)
    
    class Meta:
        model = Notification
        fields = [
            'id', 'title', 'notification_type', 'notification_type_display',
            'level', 'level_display', 'is_read', 'created_at',
            'order_id', 'recipient_role', 'recipient_real_name', 'from_location', 'expected_delivery_time'
        ]
        read_only_fields = [
            'id', 'notification_type_display', 'level_display', 'created_at',
            'order_id', 'recipient_role', 'recipient_real_name', 'from_location', 'expected_delivery_time'
        ]
    
    @extend_schema_field(OpenApiTypes.STR)
    def get_recipient_role(self, obj):
        """获取接收者身份"""
        # 首先检查订单关联关系
        if obj.related_order:
            if obj.recipient == obj.related_order.shipper:
                return 'shipper'
            elif obj.recipient == obj.related_order.driver:
                return 'driver'
        
        # 如果没有订单关联或关联不匹配，则基于用户当前角色判断
        if obj.recipient.role == User.Role.SHIPPER:
            return 'shipper'
        elif obj.recipient.role == User.Role.DRIVER:
            return 'driver'
        
        return None
    
    @extend_schema_field(OpenApiTypes.STR)
    def get_recipient_real_name(self, obj):
        """获取接收者真实姓名"""
        if (hasattr(obj.recipient, 'profile') and 
            obj.recipient.profile and 
            obj.recipient.profile.real_name):
            return obj.recipient.profile.real_name
        return None
